package com.strato.saas.merchant.interceptor.v1_0_0;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.strato.annotation.osgi.v1_0_0.service.OsgiService;
import com.strato.mvc.api.v1_0_0.control.HttpInvoker;
import com.strato.mvc.api.v1_0_0.control.HttpInvokerInterceptor;
import com.strato.mvc.api.v1_0_0.control.PathVariableCollector;
import com.strato.mvc.api.v1_0_0.model.ModelAndView;
import com.strato.mvc.api.v1_0_0.user.Principal;
import com.strato.mvc.api.v1_0_0.user.SaasPrincipal;
import com.strato.mvc.api.v1_0_0.util.RequestMeta;
import com.strato.saas.merchant.v1_0_0.MerchantContextHolder;

@OsgiService
public class MerchantHolderInterceptor implements HttpInvokerInterceptor {

	private static final int ORDER = 111;

	@Override
	public boolean canHandle(HttpServletRequest request, HttpServletResponse response, PathVariableCollector pvc, RequestMeta meta, HttpInvoker invoker) {
		return true;
	}

	@Override
	public boolean beforeInvocation(HttpServletRequest request, HttpServletResponse response, PathVariableCollector pvc, ModelAndView mav,HttpInvoker invoker) {
		Principal principal=(Principal) request.getSession().getAttribute(Principal.ATTR_PRINCIPAL_IN_SESSION);
		if(principal!=null&&principal instanceof SaasPrincipal){
			SaasPrincipal saasPrincipal=(SaasPrincipal) principal;
			String merchantId = saasPrincipal.getMerchantId();
			MerchantContextHolder.set(merchantId);
		}
		return true;
	}

	@Override
	public void invocationSuccess(HttpServletRequest request, HttpServletResponse response, PathVariableCollector pvc, ModelAndView mav, HttpInvoker invoker) {
	}

	@Override
	public void invokeFinally(HttpServletRequest request, HttpServletResponse response, PathVariableCollector pvc, HttpInvoker invoker) {
		MerchantContextHolder.set(null);
	}

	@Override
	public void invocationFailed(HttpServletRequest request, HttpServletResponse response, PathVariableCollector pvc, Exception e, HttpInvoker invoker) {
	}

	@Override
	public int getOrder() {
		return ORDER;
	}

}
